package com.hst.capacity.application.exchange.huwo.biz.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hst.capacity.application.exchange.huwo.biz.DataExchangeBiz;
import com.hst.capacity.application.thirdparty.alitrip.model.Merchant;
import com.hst.capacity.domain.common.constants.Constants;
import com.hst.capacity.domain.common.constants.HashMapConstants;
import com.hst.capacity.domain.model.entity.driver.DriverEntity;
import com.hst.capacity.domain.model.entity.driver.DriverProfileEntity;
import com.hst.capacity.domain.model.entity.exchange.huwo.HuwoOrderEntity;
import com.hst.capacity.domain.model.entity.franchisee.commision.FranchiseeCommisionEntity;
import com.hst.capacity.domain.model.entity.order.pool.OrderPoolEntity;
import com.hst.capacity.domain.model.entity.setting.airport.AirportEntity;
import com.hst.capacity.domain.model.entity.setting.price.AirportCommonPriceEntity;
import com.hst.capacity.domain.model.entity.vehicle.VehicleEntity;
import com.hst.capacity.domain.model.entity.vehicle.VehicleProfileEntity;
import com.hst.capacity.application.exchange.huwo.model.request.DriverHuwoParam;
import com.hst.capacity.application.exchange.huwo.model.request.FranchiseeHuwoParam;
import com.hst.capacity.infra.persistence.jpa.driver.DriverProfileRepository;
import com.hst.capacity.infra.persistence.jpa.driver.DriverRepository;
import com.hst.capacity.infra.persistence.jpa.exchange.huwo.HuwoOrderRepository;
import com.hst.capacity.infra.persistence.jpa.order.express.ExOrderRepository;
import com.hst.capacity.infra.persistence.jpa.order.pool.OrderPoolRepository;
import com.hst.capacity.infra.persistence.jpa.setting.commision.FranchiseeCommisionRepository;
import com.hst.capacity.infra.persistence.jpa.setting.price.AirportCommonPriceRepository;
import com.hst.capacity.infra.persistence.jpa.setting.station.AirportRepository;
import com.hst.capacity.infra.persistence.jpa.vehicle.VehicleProfileRepository;
import com.hst.capacity.infra.persistence.jpa.vehicle.VehicleRepository;
import com.hst.capacity.infra.util.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DataExchangeBizImpl implements DataExchangeBiz {

    @Autowired
    private DriverRepository driverRepository;
    @Autowired
    private DriverProfileRepository driverProfileRepository;
    @Autowired
    private VehicleRepository vehicleRepository;
    @Autowired
    private VehicleProfileRepository vehicleProfileRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private HuwoOrderRepository huwoOrderRepository;
    @Autowired
    private AirportRepository airportRepository;

    @Autowired
    OrderPoolRepository orderPoolRepository;
    @Autowired
    AirportCommonPriceRepository airportCommonPriceRepository;
    @Autowired
    FranchiseeCommisionRepository franchiseeCommisionRepository;

    @Data
    private class CityInfo {
        private String city;
        private String regionCode;
        private String idFranchisee;
    }

    @Data
    private class CarInfo {
        private String carColor;
        private String carBrand;
        private String carNo;
        private String name;
        private String mobile;
        private String carModel;
    }

    @Override
    public Boolean saveDriverHuwo(List<DriverHuwoParam> driverList) {

        for (int i = 0; i < driverList.size(); i++) {
            try {
                DriverHuwoParam dhw = driverList.get(i);
                CityInfo cityInfo = this.readJsonCityInfo(dhw.getId_huwo());

                String driverMemo = String.format("呼我[id_driver]:%s", dhw.getId_driver());
                String idDriverProfile = StringUtil.generateUuid();
                String idDriver = StringUtil.generateUuid();
                String idVehicle = StringUtil.generateUuid();

                DriverProfileEntity dp = driverProfileRepository.findByIdCardNo(dhw.getId_card());
                if (dp == null) {
                    dp = new DriverProfileEntity();
                    dp.setIdDriverProfile(idDriverProfile);
                    dp.setGender(dhw.getGender());
                    dp.setRealName(dhw.getName());
                    dp.setIdCardNo(dhw.getId_card());
                    dp.setJobType(1);
                    dp.setServiceScope(String.valueOf(Constants.OrderModuleType.SPECIAL));
                    dp.setMemo(driverMemo);
                    dp = driverProfileRepository.save(dp);
                } else {
                    idDriverProfile = dp.getIdDriverProfile();
                }

                VehicleEntity v = vehicleRepository.findAllByPlateNumber(dhw.getPlate_number());
                if (v == null) {
                    v = new VehicleEntity();
                    v.setIdVehicle(idVehicle);
                    v.setIdFranchisee(cityInfo.getIdFranchisee());
                    v.setIdVehicleType(dhw.getId_vehicle_type());
                    v.setPlateNumber(dhw.getPlate_number());
                    v.setVehicleName(dhw.getBrand());
                    v.setEmployee(idDriver);
                    v.setState(0);//todo
                    v.setCommercialType(0);
                    v = vehicleRepository.save(v);
                } else {
                    idVehicle = v.getIdVehicle();
                }

                VehicleProfileEntity vp;
                vp = vehicleProfileRepository.findByIdVehicle(v.getIdVehicle());
                if (vp == null) {
                    vp = new VehicleProfileEntity();
                    vp.setIdVehicleProfile(StringUtil.generateUuid());
                    vp.setIdVehicle(v.getIdVehicle());
                }
                vp.setBrand(dhw.getBrand());
                vp.setColor(dhw.getColor());
                vp.setModel(dhw.getModel());
                vp = vehicleProfileRepository.save(vp);

                DriverEntity d = driverRepository.findByDriverMobile(dhw.getMobile());
                if (d == null) {
                    d = new DriverEntity();
                    d.setIdDriver(StringUtil.generateUuid());
                    d.setDriverMobile(dhw.getMobile());
                    d.setIdFranchisee(cityInfo.getIdFranchisee());
                    d.setRegionCode(cityInfo.getRegionCode());
                    d.setIdDriverProfile(dp.getIdDriverProfile());
                    d.setCreateOrderRole(0);//0：无权限
                    d.setIsAgreement(1);
                    d.setStatus(0);
                    d.setOperationStatus(9);//todo 待确认
                    d.setRegisterDate(LocalDateTime.now());
                    d.setRegisterFrom("dataExchange");
                    d.setPassword("50D9409DFDF3BAFB72A0E68131D111F");
                    d.setLoginFailureTimes(0);
                    d.setIdDriverProfile(idDriverProfile);
                    d.setIdVehicle(idVehicle);
                    d = driverRepository.save(d);
                } else {
                    d.setIdFranchisee(cityInfo.getIdFranchisee());
                    d.setRegionCode(cityInfo.getRegionCode());
                    d.setIdDriverProfile(dp.getIdDriverProfile());
                    d.setCreateOrderRole(0);//0：无权限
                    d.setIsAgreement(1);
                    d.setStatus(0);
                    d.setOperationStatus(9);//todo 待确认
                    d.setRegisterDate(LocalDateTime.now());
                    d.setRegisterFrom("dataExchange");
                    d.setLoginFailureTimes(0);
                    d.setIdDriverProfile(idDriverProfile);
                    d.setIdVehicle(idVehicle);
                    d = driverRepository.save(d);
                }
            } catch (Exception e) {
                log.info(e.getMessage());
            }
        }

        return true;
    }

    @Override
    public void saveOrderHuwo() {

        List<HuwoOrderEntity> list = huwoOrderRepository.findAll();
        List<CityInfo> cityList = getHuwoCityList();
        HuwoOrderEntity huwoOrder = null;
        for (int i = 0; i < list.size(); i++) {
//            try {
                huwoOrder = list.get(i);

                CarInfo car = readJsonCarInfo(huwoOrder.getCar());

                String driverMobile = huwoOrder.getDriverMobile();
                if (StringUtil.isBlank(driverMobile))
                    driverMobile = car.getMobile();
                DriverEntity d = driverRepository.findByDriverMobile(driverMobile);

                List<AirportEntity> airList = airportRepository.findFirstByIata(huwoOrder.getFlightCode());
                String idAirport = null;
                if (airList != null && airList.size() > 0) {
                    idAirport = airList.get(0).getIdAirport();
                }

                String merchantStr = HashMapConstants.HuwoMap.get(String.valueOf(huwoOrder.getTeamId()));
                JSONObject merchant = JSON.parseObject(merchantStr);
                String idFranchisee = merchant.getString("idFranchisee");

                OrderPoolEntity order;
                int use_car_type = huwoOrder.getUseCarType();
                if (use_car_type == 9){
                    use_car_type = 6;
                }else{
                    use_car_type = use_car_type - 1;
                }

                Integer idServiceType = 0;
                if(huwoOrder.getFromInfo().contains("机场")) {
                    idServiceType= Constants.ServiceType.AIRPORT_PICK;
                }
                if(huwoOrder.getToInfo().contains("机场")){
                    idServiceType= Constants.ServiceType.AIRPORT_SEND;
                }

                AirportCommonPriceEntity airportCommonPriceEntity = airportCommonPriceRepository.findByIdAirport(idFranchisee,idAirport,idServiceType,1,Constants.Channel.ALITRIP);
                String id_service_price_type = "0";
                if (airportCommonPriceEntity != null)
                    id_service_price_type = airportCommonPriceEntity.getIdServicePriceType();

                String idOrder = "ZCHW" + huwoOrder.getOrderNo().toString();
                order = orderPoolRepository.findByIdOrder(idOrder);
                if (order == null)
                    order = new OrderPoolEntity();
                CityInfo cityInfo = getIdFranchiseeByCity(cityList, huwoOrder.getCity());
                String idDriver = null;
                if(d != null) {
                    idDriver = d.getIdDriver();
                }
                String[] startAddress = huwoOrder.getFrom_point().split(",");
                String[] endAddress = huwoOrder.getTo_point().split(",");
                String startAddressLongitude=null;//上车经度
                String startAddressLatitude=null;//上车维度
                String endAddressLongitude=null;//预计下车经度
                String endAddressLatitude=null;//预计下车维度
                // todo
                if (startAddress!=null){
                    startAddressLongitude = startAddress[0];
                    startAddressLatitude = startAddress[1];
                }
                if (endAddress!=null){
                    endAddressLongitude = endAddress[0];
                    endAddressLatitude = endAddress[1];
                }

                String driverMemo =  "电话："+ car.getMobile() + ",车牌号：" + car.getCarNo();
                String orderMemo = huwoOrder.getTeamTitle();
                String driverInfo;
                if (StringUtil.isNotBlank(huwoOrder.getDriverMobile()))
                    driverInfo = huwoOrder.getDriverMobile() + "/" + huwoOrder.getDriverName();
                else
                    driverInfo = car.getMobile();

                order.setIdOrder(idOrder);
                order.setExternalOrderId(huwoOrder.getOrderId());
                order.setAppointmentTime(huwoOrder.getUseLocalDate());
                order.setAssignTime(huwoOrder.getCreateDate());
                order.setDeptime(null);
                order.setDesttime(null);
                order.setStartServiceTime(null);
                order.setEndServiceTime(null);
                // todo
                order.setIdStation( null );
                order.setIdMember("huwo25597022");
                order.setIdDriver(idDriver);
                order.setIdFranchisee( idFranchisee );
                order.setIdBrandHolder("Huwo");
                // todo
                order.setFullName( null );
                // todo
                order.setIdServicePriceType(id_service_price_type);
                order.setIdServiceType( idServiceType );
                order.setIdVehicleType( use_car_type );
                order.setIdTask( null );
                // todo
                order.setOrderType( Constants.OrderType.APPOINTMENT );
                // todo
                order.setCarpoolType(Constants.OrderCarpoolType.Chartered );
                order.setIdAirport(idAirport);
                order.setFlightNo(huwoOrder.getFlightNo());
                // todo
                order.setRailNo(null);
                order.setAdditionalMoney( 0f );
                order.setUserName( huwoOrder.getTravelName() );
                order.setUserMobile( huwoOrder.getTravel_phone() );
                order.setPassengerName( huwoOrder.getTravelName() );
                order.setPassengerMobile( huwoOrder.getTravel_phone() );
                // todo
                order.setPassengerNumber( 1 );
                order.setDriverLongitude( startAddressLongitude );
                order.setDriverLatitude( startAddressLatitude );
                order.setStartAddress( huwoOrder.getFromInfo() );
                order.setStartAddressLongitude( startAddressLongitude );
                order.setStartAddressLatitude( startAddressLatitude );
                order.setEndAddress( huwoOrder.getToInfo() );
                order.setEndAddressLongitude( endAddressLongitude );
                order.setEndAddressLatitude( endAddressLatitude );
                if (huwoOrder.getState() == 23) {
                    order.setDropOffArea(huwoOrder.getToInfo());
                    order.setDropOffAreaLongitude(endAddressLongitude);
                    order.setDropOffAreaLatitude(endAddressLatitude);
                }
                order.setReferenceDistance(Float.valueOf(huwoOrder.getUseDistance()/1000));
                order.setEstimatedTime( huwoOrder.getUseTime()/60 );
                order.setEstimatedMoney( huwoOrder.getTotal() );
                order.setPayMoney( huwoOrder.getPayTotal() );
                order.setCouponCode( null );
                float coupon = huwoOrder.getTotal() - huwoOrder.getPayTotal();
                order.setCouponDiscount(coupon);
                order.setShopCouponDiscount( 0f );
                // todo
                order.setOrderSource( Constants.OrderSource.ALITRIP);
                order.setPaymentType( Constants.PaymentType.ALIPAY);
                order.setPaymentStatus( Constants.PaymentStatus.ON_PAY );
                order.setPaymentRequitment( Constants.PaymentRequitment.PAY_ALITRIP );
                order.setStatus( HashMapConstants.HuwoOrderStateMap.get(huwoOrder.getState()) );
                order.setOrderMemo( orderMemo );
                order.setDriverMemo( driverMemo );
                order.setPassengerMemo( huwoOrder.getInvoice() );
                order.setOrderMoney( huwoOrder.getTotal() );
                FranchiseeCommisionEntity franchiseeCommisionEntity = null;
                if (StringUtil.isNotBlank(order.getIdFranchisee()))
                    franchiseeCommisionEntity = franchiseeCommisionRepository.findByChannelAndIdFranchiseeAndModuleType(
                            Constants.Channel.ALITRIP, order.getIdFranchisee(), Constants.OrderModuleType.SPECIAL);
                float driverIncome = order.getEstimatedMoney() * 0.75f;
                if (franchiseeCommisionEntity != null) {
                    driverIncome = order.getEstimatedMoney() * franchiseeCommisionEntity.getDriverRate() / 100;
                }
                order.setDriverIncome(driverIncome);
                order.setSubBizType( 0 );
                order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);

                order.setDriverInfo(driverInfo);
                order.setPlateNumber(car.getCarNo());
                order.setVehicleInfo(car.carBrand);
                order.setCreateTime(huwoOrder.getCreateDate());
                order.setCreateBy("Huwo");
                order.setRegionCode( cityInfo.getRegionCode() );
                order.setOrderPriority(0);
                orderPoolRepository.save(order);

//            } catch (Exception e) {
//                if (huwoOrder != null)
//                    log.info(JSON.toJSONString(huwoOrder));
//            }
        }
    }

    @Override
    public void updateHuwoOrder() {

        List<HuwoOrderEntity> list = huwoOrderRepository.findAll();
        HuwoOrderEntity huwoOrder = null;
        for (int i = 0; i < list.size(); i++) {
            try {
                huwoOrder = list.get(i);
                OrderPoolEntity order;
                String idOrder = "ZCHW" + huwoOrder.getOrderNo();
                order = orderPoolRepository.findByIdOrder(idOrder);
                if (order != null) {
//                String[] endAddress = huwoOrder.getTo_point().split(",");
//                String endAddressLongitude=null;//预计下车经度
//                String endAddressLatitude=null;//预计下车维度
//                // todo
//                if (endAddress!=null){
//                    endAddressLongitude = endAddress[0];
//                    endAddressLatitude = endAddress[1];
//                }
//                order.setEndAddress( huwoOrder.getToInfo() );
//                order.setEndAddressLongitude( endAddressLongitude );
//                order.setEndAddressLatitude( endAddressLatitude );

                    order.setEstimatedMoney(huwoOrder.getTotal());
                    order.setPayMoney(huwoOrder.getPayTotal());
                    float coupon = huwoOrder.getTotal() - huwoOrder.getPayTotal();
                    order.setCouponDiscount(coupon);
                    order.setOrderMoney(huwoOrder.getTotal());
                    FranchiseeCommisionEntity franchiseeCommisionEntity = null;
                    if (StringUtil.isNotBlank(order.getIdFranchisee()))
                        franchiseeCommisionEntity = franchiseeCommisionRepository.findByChannelAndIdFranchiseeAndModuleType(
                                Constants.Channel.ALITRIP, order.getIdFranchisee(), Constants.OrderModuleType.SPECIAL);
                    float driverIncome = order.getEstimatedMoney() * 0.75f;
                    if (franchiseeCommisionEntity != null) {
                        driverIncome = order.getEstimatedMoney() * franchiseeCommisionEntity.getDriverRate() / 100;
                    }
                    order.setDriverIncome(driverIncome);

                    orderPoolRepository.save(order);
                }
            } catch (Exception e) {
                if (huwoOrder != null)
                    log.info(JSON.toJSONString(huwoOrder));
            }
        }
    }

    private CityInfo readJsonCityInfo(String idHuwo) {

        String value = HashMapConstants.HuwoMap.get(idHuwo);
        com.alibaba.fastjson2.JSONObject jsonObject = JSON.parseObject(value);
        String city = jsonObject.getString("city");
        String regionCode = jsonObject.getString("regionCode");
        String idFranchisee = jsonObject.getString("idFranchisee");

        CityInfo cityInfo = new CityInfo();
        cityInfo.setCity(city);
        cityInfo.setRegionCode(regionCode);
        cityInfo.setIdFranchisee(idFranchisee);

        return cityInfo;
    }

    private CarInfo readJsonCarInfo(String carInfo) {

        String value = StringUtil.UnicodeToChinese(carInfo);
        com.alibaba.fastjson2.JSONObject jsonObject = JSON.parseObject(value);
        String mobile = jsonObject.getString("mobile");
        mobile = mobile.replace("+86","");
        mobile = mobile.trim();
        CarInfo car = new CarInfo();
        car.setCarNo(jsonObject.getString("car_no"));
        car.setCarColor(jsonObject.getString("car_color"));
        car.setCarBrand(jsonObject.getString("car_brand"));
        car.setMobile(mobile);
        car.setName(jsonObject.getString("name"));
        car.setCarModel(jsonObject.getString("car_model"));
        return car;
    }

    private List<CityInfo> getHuwoCityList() {
        List<CityInfo> list = new ArrayList<>();

        for ( String key : HashMapConstants.HuwoMap.keySet() ) {
            String value = HashMapConstants.HuwoMap.get(key);
            com.alibaba.fastjson2.JSONObject jsonObject = JSON.parseObject(value);
            String city = jsonObject.getString("city");
            String regionCode = jsonObject.getString("regionCode");
            String idFranchisee = jsonObject.getString("idFranchisee");

            CityInfo cityInfo = new CityInfo();
            cityInfo.setCity(city);
            cityInfo.setRegionCode(regionCode);
            cityInfo.setIdFranchisee(idFranchisee);

            list.add(cityInfo);
        }
        return list;
    }

    private FranchiseeHuwoParam.Content getIdFranchiseeByIdHuwo(List<FranchiseeHuwoParam> franchiseeList,String idHuwo){

        for (FranchiseeHuwoParam f : franchiseeList) {
            if (f.getIdHuwo().equals(idHuwo)){
                return f.getContent();
            }
        }
        return null;
    }

    private CityInfo getIdFranchiseeByCity(List<CityInfo> cityList, String city){

        for (CityInfo c : cityList) {
            if (c.getCity().equals(city)){
                return c;
            }
        }
        return null;
    }


}
